package com.zyh.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.server.config.Constant;
import com.zyh.server.entity.Goods;
import com.zyh.server.entity.MiaoshaGoods;
import com.zyh.server.service.GoodsService;
import com.zyh.server.service.MiaoshaGoodsService;
import com.zyh.server.utils.R;
import com.zyh.server.utils.RedisUtil;
import com.zyh.server.vo.MiaoshaGoodsVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @Author: zyh
 * @Date: 2024-11-18-9:53
 * @Description
 */
@Slf4j
@Tag(name = "秒杀模块")
@RestController
@RequestMapping("/miaoshaGoods")
@CrossOrigin(origins = "*")
public class MiaoshaGoodsController {
	@Autowired
	private MiaoshaGoodsService miaoshaGoodsService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private RedisUtil redisUtil;

	@Operation(summary = "新增或更新秒杀商品信息")
	@Parameters({@Parameter(name = "miaoshaGoods", description = "秒杀商品详情")})
	@PostMapping("/saveOrUpdate")
	public R saveOrUpdate(@RequestBody MiaoshaGoods miaoshaGoods) {
		log.info("查看参数miaoshaGoods : {}", miaoshaGoods);
		boolean flag = miaoshaGoodsService.saveOrUpdate(miaoshaGoods);
		// 判断是修改还是新增商品
		if (miaoshaGoods.getMiaoshaId() != null && flag) {
			// 更新redis缓存
			// 从redis中取出这个对象
			Object obj = redisUtil.getObj(Constant.REDIS_MIAOSHA_GOODS_PREFIX + miaoshaGoods.getMiaoshaId());
			// 如果对象不为空
			if (Objects.nonNull(obj)) {
				// 类型转换
				MiaoshaGoodsVO miaoshaGoodsVO = new ObjectMapper().convertValue(obj, MiaoshaGoodsVO.class);
				miaoshaGoodsVO.setMiaoshaPrice(miaoshaGoods.getMiaoshaPrice());
				miaoshaGoodsVO.setMiaoshaStock(miaoshaGoods.getMiaoshaStock());
				miaoshaGoodsVO.setStartTime(miaoshaGoods.getStartTime());
				miaoshaGoodsVO.setEndTime(miaoshaGoods.getEndTime());
				// 重新存入redis中
				redisUtil.saveObj(Constant.REDIS_MIAOSHA_GOODS_PREFIX + miaoshaGoods.getMiaoshaId(), miaoshaGoodsVO, Constant.REDIS_MIAOSHA_GOODS_EXPIRE);
			}
		}
		return flag ? R.ok("秒杀商品更新成功！") : R.fail("秒杀商品更新失败！");
	}

	@Operation(summary = "根据商品id查询商品信息")
	@Parameters({@Parameter(name = "goodsId", description = "秒杀商品id")})
	@GetMapping("/getMiaoshaGoodsById/{goodsId}")
	public R getMiaoshaGoodsById(@PathVariable Integer goodsId) {
		log.info("查看参数goodsId : {}", goodsId);
		QueryWrapper<MiaoshaGoods> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("goods_id", goodsId);
		MiaoshaGoods miaoshaGoods = miaoshaGoodsService.getOne(queryWrapper);
		if (Objects.isNull(miaoshaGoods)) {
			miaoshaGoods = new MiaoshaGoods();
		}
		// 查询出goods
		Goods goods = goodsService.getById(goodsId);
		miaoshaGoods.setGoods(goods);
		return R.ok().setData(miaoshaGoods);
	}

	@Operation(summary = "查看所有秒杀商品(分页)")
	@Parameters({
			@Parameter(name = "pageNum", description = "当前页码", in = ParameterIn.QUERY),
			@Parameter(name = "pageSize", description = "每页显示记录数", in = ParameterIn.QUERY),
			@Parameter(name = "goodsName", description = "搜索关键字", in = ParameterIn.QUERY)
	})
	@GetMapping("/getGoodsByPage")
	public R getGoodsByPage(
			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
			@RequestParam(value = "goodsName", defaultValue = "") String goodsName) {
		log.info("请求商品列表页码:{},每页显示记录数:{},搜索关键字:{}", pageNum, pageSize, goodsName);
		IPage<MiaoshaGoodsVO> miaoshaGoodsList = miaoshaGoodsService.findGoodsByPage(pageNum, pageSize, goodsName);
		return R.ok().setData(miaoshaGoodsList);
	}

	@Operation(summary = "根据id查询秒杀商品详细信息")
	@Parameters({@Parameter(name = "miaoshaGoodsId", description = "秒杀商品id")})
	@GetMapping("/detail/{miaoshaGoodsId}")
	public R miaoshaGoodsDetails(@PathVariable("miaoshaGoodsId") Integer miaoshaGoodsId) {
		log.info("查看参数miaoshaGoodsId : {}", miaoshaGoodsId);
		MiaoshaGoodsVO miaoshaGoodsVO = null;
		// 先从redis中获取秒杀商品信息
		Object obj = redisUtil.getObj(Constant.REDIS_MIAOSHA_GOODS_PREFIX + miaoshaGoodsId);
		if (Objects.isNull(obj)) {
			log.info("redis中不存在秒杀商品信息，从数据库中获取");
			// 不存在就从数据库中查询
			miaoshaGoodsVO = miaoshaGoodsService.miaoshaGoodsDetails(miaoshaGoodsId);
		} else {
			// redis中存在秒杀商品信息
			log.info("redis中存在秒杀商品信息,从redis中获取");
			// 格式转换，将Object类型转为对应的数据类型
			miaoshaGoodsVO = new ObjectMapper().convertValue(obj, MiaoshaGoodsVO.class);
		}
		//秒杀状态
		Integer miaoShaStatus = 0;
		//秒杀开始，倒计时
		Integer remainBeginSecond = -1;
		//秒杀结束，倒计时
		Integer remainEndSecond = -1;
		//<1> 获取三个时间的毫秒数  Date-->long
		long startTime = miaoshaGoodsVO.getStartTime().getTime();
		long endTime = miaoshaGoodsVO.getEndTime().getTime();
		long currentTime = System.currentTimeMillis();
		if (currentTime < startTime) {
			//秒杀未开始
			miaoShaStatus = 0;
			remainBeginSecond = (int) (startTime - currentTime) / 1000; //求还有多少秒开始
			remainEndSecond = (int) (endTime - currentTime) / 1000;
		} else if (currentTime > endTime) {
			//秒杀结束
			miaoShaStatus = 2;
			remainBeginSecond = -1;
			remainEndSecond = -1;
		} else {
			//秒杀进行中
			miaoShaStatus = 1;
			remainBeginSecond = -1;
			remainEndSecond = (int) (endTime - currentTime) / 1000; //求还有多少秒结束
		}
		miaoshaGoodsVO.setMiaoShaStatus(miaoShaStatus);
		miaoshaGoodsVO.setRemainBeginSecond(remainBeginSecond);
		miaoshaGoodsVO.setRemainEndSecond(remainEndSecond);
		// 查询出来的结果存入redis
		redisUtil.saveObj(Constant.REDIS_MIAOSHA_GOODS_PREFIX + miaoshaGoodsId,
				miaoshaGoodsVO,
				Constant.REDIS_MIAOSHA_GOODS_EXPIRE);
		return R.ok().setData(miaoshaGoodsVO);
	}
}
